﻿using System;
using System.Collections.Generic;
#if DEBUG
using System.Diagnostics;
#endif // #if DEBUG
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using FRL.DebtChased.Extensions;
using FRL.DebtChased.Repository;
using FRL.DebtChased.Silverlight.Library.RichContentService;
using FRL.DebtChased.Silverlight.Library;
using FRL.DebtChased.AgentEditor;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Windows.Data;


namespace FRL.DebtChased.Views
{
    public partial class AgentCtrl : UserControl
    {
        public AgentCtrl()
        {
            InitializeComponent();

            			// Set up event handlers
			//ctrlDetailsAndBank.agentDetailsCtrl.AgentTypeChanged += new EventHandler(CtrlAgentDetails_AgentTypeChanged);

			// Setup controls
			_setupControls();

             //ObservableCollection<ContactTransport> Contacts = new ObservableCollection<ContactTransport>();
             //tabContacts.Contacts = Contacts;

        }

        public void PostStartDataLoad()
        {
            // Load the search combobox
            //foreach (var di in CachedData.Singleton.CountryMap)
            //    cboSearchCode.Items.Add(new ComboBoxObject(di.Value, 0, di.Key));
            //ComboBoxObject.SelectByTagString(cboSearchCode, "UK");

            // Set controls
            //ctrlDetailsAndBank.PostSupportDataLoaded();

        }
        public void SetupControls()
        {
            _setupControls();

        }

        public void PostLoad()
        {
            // If there is an agent to load...
            if (m_iCurrentAgentId != 0)
            {

                // Load the agent
                _loadAgent();

            }
            else
            {

                // Create an empty agent to edit
                _setNewAgent();

                // Setup controls
                _setupControls();

            }

        }

        
		/////////////////////////////////////////////////////////////
		// Attributes

		private int m_iCurrentAgentId = 0;

		/////////////////////////////////////////////////////////////
		// Construction


		/////////////////////////////////////////////////////////////
		// Event Handlers

		private void butNew_Click(object sender, RoutedEventArgs e)
		{

			// Confirmation
			if (!MessageBoxes.PopupOption("Discard current agent details?"))
				return;

			// Set a new agent
			_setNewAgent();

			// Setup controls
			_setupControls();

		}

		private void butSave_Click(object sender, RoutedEventArgs e)
		{

			// Get the agent details
			AgentTransport agent = _getAgent();
			if (agent == null)
				return;

			// Confirmation
			if (!MessageBoxes.PopupOption("Save changes to agent?"))
				return;

			// Save the agent
			_saveAgent(agent);

		}

		private void butRevert_Click(object sender, RoutedEventArgs e)
		{

			// Reload the agent
			_loadAgent();

		}

		private void butSearch_Click(object sender, RoutedEventArgs e)
		{

			// Get the country code
			//string strSearch = (cboSearchCode.SelectedValue as ComboBoxObject).Tag.ToString();
			//_startSearch(strSearch);

		}

		private void CtrlAgentDetails_AgentTypeChanged(object sender, EventArgs e)
		{

			// Update titles
			_updateTitles();

		}

		void CtrlAgentDetails_AgentNameChanged(object sender, EventArgs e)
		{

			// Update top-title
			_updateTopTitle();

		}

		/////////////////////////////////////////////////////////////
		// Operations

		public void _setupControls()
		{

			// Enable/disable buttons
			//butRevert.IsEnabled = (m_iCurrentAgentId != 0);
			//cboSearchCode.IsEnabled = (cboSearchCode.Items.Count > 0);
			//butSearch.IsEnabled = (cboSearchCode.Items.Count > 0);

		}

		private AgentTransport _getAgent()
		{

			// Populate the agent object with details from the control
			// and display errors in the user input

			// Declare return variable
			AgentTransport Ftmp = new AgentTransport();
			Ftmp.AgentId = m_iCurrentAgentId;
			Ftmp.CoverageCountryCodes = new System.Collections.ObjectModel.ObservableCollection<string>();
			Ftmp.Contacts = new System.Collections.ObjectModel.ObservableCollection<ContactTransport>();
			Ftmp.BankAccounts = new System.Collections.ObjectModel.ObservableCollection<BankAccountTransport>();

			// Declaration of local variables
			List<string> Errors = new List<string>();

			// Update from controls
			//ctrlDetailsAndBank.Get(Ftmp,Errors);

			// Get the contacts
			List<ContactTransport> contacts = tabContacts.Get(Errors);
			foreach (ContactTransport contact in contacts)
				Ftmp.Contacts.Add(contact);
			if (contacts.Count == 0)
				Errors.Add("The agent must have at least one contact.");

			// If there are errors...
			if (Errors.Count > 0)
			{

				// Convert errors
				if(Ftmp.AgentType == (int)Definitions.eAgentType.Solicitor)
				{					
					for(int i1=0; i1<Errors.Count; i1++ )
					{
						string strError = Errors[i1];
						Errors.RemoveAt(i1);
						strError = strError.Replace("agent","solicitor");
						Errors.Insert(i1,strError);
					}
				}

				// Show errors
				MessageBoxes.PopupErrors(Errors);

				// Nullify reference
				Ftmp = null;

			}

			// Return variable
			return Ftmp;

		}

		private void _setNewAgent()
		{

			// Reset id
			m_iCurrentAgentId = 0;

			// Set controls from an empty agent
			AgentTransport agentTransport = new AgentTransport();
			agentTransport.UseAccountCommissionRate = true;
			agentTransport.AgentType = (int)Definitions.eAgentType.Agent;
			agentTransport.BankAccounts = new System.Collections.ObjectModel.ObservableCollection<BankAccountTransport>();
			agentTransport.CoverageCountryCodes = new System.Collections.ObjectModel.ObservableCollection<string>();
			agentTransport.Contacts = new System.Collections.ObjectModel.ObservableCollection<ContactTransport>();
			_setAgent(agentTransport);

		}

		private void _setAgent(AgentTransport agentTransport)
		{

			// Set controls
			//ctrlDetailsAndBank.Set(agentTransport,false);
            tabContacts.Contacts = agentTransport.Contacts;

		}

		private void _updateTitles()
		{
            /*
			// Update top title
			_updateTopTitle();

			// Get the agent type
			Definitions.eAgentType agentType = (Definitions.eAgentType)(ctrlDetailsAndBank.agentDetailsCtrl.cboType.SelectedValue as ComboBoxObject).ItemData;

			// Compose title
			if(agentType == Definitions.eAgentType.Agent)
			{

				// Set panel titles
				headAgentDetails.Label = "Agent Details & Bank Accounts";
				//barStatsAndInfo.Label = "Agent Performance";
				//barAgentContacts.Label = "Agent Contacts";

			}
			else
			{

				// Set panel titles
				headAgentDetails.Label = "Solicitor Details & Bank Accounts";
				//barStatsAndInfo.Label = "Solicitor Performance";
				//barAgentContacts.Label = "Solicitor Contacts";

			}
            /**/
		}

		private void _updateTopTitle()
		{
            /*
			// Get the agent type
			Definitions.eAgentType agentType = (Definitions.eAgentType)(ctrlDetailsAndBank.agentDetailsCtrl.cboType.SelectedValue as ComboBoxObject).ItemData;

			// Compose title
			if (agentType == Definitions.eAgentType.Agent)
			{

				// Top title
				if (ctrlDetailsAndBank.agentDetailsCtrl.txtAgentName.Text.Length == 0)
					tbAgentDetailsPanelTitle.Text = "Agent";
				else
					tbAgentDetailsPanelTitle.Text = string.Format("Agent - {0}", ctrlDetailsAndBank.agentDetailsCtrl.txtAgentName.Text);

			}
			else
			{

				// Top title
				if (ctrlDetailsAndBank.agentDetailsCtrl.txtAgentName.Text.Length == 0)
					tbAgentDetailsPanelTitle.Text = "Solicitor";
				else
					tbAgentDetailsPanelTitle.Text = string.Format("Solicitor - {0}", ctrlDetailsAndBank.agentDetailsCtrl.txtAgentName.Text);

			}
            /**/
		}

		/////////////////////////////////////////////////////////////
		// Rich content service operations


		private void _loadAgent()
		{
#if DEBUG
			Debug.Assert(m_iCurrentAgentId != 0);
#endif // #if DEBUG

			// Show hourglass
			MainPage.Singleton.gridHourglass.IncShowCount(true);

			try
			{

				// Load the agent
#if USEFAKEDATA

			// Create event
			object[] results = new object[1];
			results[0] = CachedData.GetDummyAgentTransport();
			GetAgentCompletedEventArgs e = new GetAgentCompletedEventArgs(
				results,
				null,
				false,
				null
			);

			// Process fake agent data
			proxy_GetAgentCompleted(null, e);

#else

				// Download the agent
				RichContentServiceClient proxy = new RichContentServiceClient();
				proxy.GetAgentCompleted += new EventHandler<GetAgentCompletedEventArgs>(proxy_GetAgentCompleted);
				proxy.Endpoint.Address = ExtensionsForSilverlight.CreateDebtChasedEndpoint();
				proxy.GetAgentAsync(m_iCurrentAgentId);

#endif // #if USEFAKEDATA

			}
			catch (Exception x)
			{

				// Message for user
				MessageBoxes.PopupMessage_InternalError(string.Format("Failed to load agent.\n\n{0} {1}", x.Message, x.InnerException.Message));

			}

		}

		void proxy_GetAgentCompleted(object sender, GetAgentCompletedEventArgs e)
		{

			// Hide hourglass
			MainPage.Singleton.gridHourglass.IncShowCount(false);

			// Get the result
			if (e.Error != null)
				MessageBoxes.PopupMessage(e.Error.Message);
			else if (e.Result == null)
				MessageBoxes.PopupMessage("Failed to load agent from server.");
			else
			{

				// Update the controls
				_setAgent(e.Result);

			}

			// Setup controls
			_setupControls();

		}

		private void _saveAgent(AgentTransport agent)
		{

			// Show hourglass
			MainPage.Singleton.gridHourglass.IncShowCount(true);

			try
			{

				// Initialize a save function
				RichContentServiceClient proxy = new RichContentServiceClient();
				proxy.SetAgentCompleted += new EventHandler<SetAgentCompletedEventArgs>(proxy_SetAgentCompleted);
				proxy.Endpoint.Address = ExtensionsForSilverlight.CreateDebtChasedEndpoint();
				proxy.SetAgentAsync(agent);

			}
			catch (Exception x)
			{

				// Message for user
				MessageBoxes.PopupMessage(string.Format("Failed to save agent.\n\n{0} {1}", x.Message, x.InnerException.Message));

			}

		}

		void proxy_SetAgentCompleted(object sender, SetAgentCompletedEventArgs e)
		{

			// Hide hourglass
			MainPage.Singleton.gridHourglass.IncShowCount(false);

			// Get the result
			if (e.Error != null)
				MessageBoxes.PopupMessage(e.Error.Message);
			else if (e.Result != null)
				MessageBoxes.PopupMessage(string.Format("Failed to save agent.  {0}", e.Result));
			else
			{
                /*
				// Update the id
				m_iCurrentAgentId = e.agentTransport.AgentId;

				// Inform the controls of the new contact ids
                tabContacts.Contacts = e.agentTransport.Contacts;
				ctrlDetailsAndBank.Set(e.agentTransport, true);
                /**/
			}

			// Setup controls
			_setupControls();

		}

		private void _startSearch(string strCode)
		{

			// Show hourglass
			MainPage.Singleton.gridHourglass.IncShowCount(true);

			try
			{

				// Initialize a save function
				RichContentServiceClient proxy = new RichContentServiceClient();
				proxy.SearchAgentsCompleted += new EventHandler<SearchAgentsCompletedEventArgs>(proxy_SearchAgentsCompleted);
				proxy.Endpoint.Address = ExtensionsForSilverlight.CreateDebtChasedEndpoint();
				proxy.SearchAgentsAsync(strCode);

			}
			catch (Exception x)
			{

				// Message for user
				MessageBoxes.PopupMessage(string.Format("Failed to search agents.\n\n{0} {1}", x.Message, x.InnerException.Message));

			}

		}

		void proxy_SearchAgentsCompleted(object sender, SearchAgentsCompletedEventArgs e)
		{

			// Hide hourglass
            MainPage.Singleton.gridHourglass.IncShowCount(false);

			// Get the result
			if (e.Error != null)
				MessageBoxes.PopupMessage(e.Error.Message);
			else if (e.Result == null)
				MessageBoxes.PopupMessage_InternalError("Failed to search agents.");
			else
			{

				// If there are some results
				if ( e.Result.Count > 0 )
				{
					SearchResultsWnd wndResults = new SearchResultsWnd(e.Result.ToList());
					wndResults.Closed += new EventHandler(wndResults_Closed);
					wndResults.Show();
				}
				else
					MessageBoxes.PopupMessage("Search returned no results.");

			}

			// Setup controls
			_setupControls();

		}

		void wndResults_Closed(object sender, EventArgs e)
		{

			// Get the selected id
			SearchResultsWnd wnd = sender as SearchResultsWnd;
			if (wnd.DialogResult == true)
			{
				m_iCurrentAgentId = wnd.SelectedAgentId;
				_loadAgent();
			}

		}

        private void ctrlDetailsAndBank_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private GridLength _gridLengthAuto = new GridLength(1, GridUnitType.Auto);
        private GridLength _gridLengthStar = new GridLength(1, GridUnitType.Star);
        private void CommentsCtrl_ExpandChange(object sender, PanelExpandChangeEventArgs e)
        {
            CommentsRow.Height = e.IsExpanded ? _gridLengthStar : _gridLengthAuto;
        }

    }
}
